package vn.com.epi.utils;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;

import vn.com.epi.data.table.ArticleTable;
import vn.com.epi.data.table.NeighbourTable;
import vn.com.epi.data.table.RecommendationTable;
import vn.com.epi.data.table.TempUserTable;
import vn.com.epi.data.table.UserTable;

public class TableUtils {

	public static void truncateTable(byte[] tableName) throws IOException {
		Configuration conf = new Configuration();
		HBaseAdmin admin = new HBaseAdmin(conf);
		try {
			truncateTable(admin, tableName);
		} finally {
			admin.close();
		}
	}

	public static void truncateTable(Configuration conf, byte[] tableName)
			throws IOException {
		HBaseAdmin admin = new HBaseAdmin(conf);
		try {
			truncateTable(admin, tableName);
		} finally {
			admin.close();
		}
	}

	public static void truncateTable(HBaseAdmin admin, byte[] tableName)
			throws IOException {
		HTableDescriptor descriptor = admin.getTableDescriptor(tableName);
		admin.disableTable(tableName);
		admin.deleteTable(tableName);
		admin.createTable(descriptor);
	}

	public static void createTable(HBaseAdmin admin, byte[] name,
			byte[]... families) throws IOException {
		if (admin.tableExists(name)) {
			return;
		}
		HTableDescriptor descriptor = new HTableDescriptor(name);
		for (int i = 0; i < families.length; i++) {
			descriptor.addFamily(new HColumnDescriptor(families[i]));
		}
		admin.createTable(descriptor);
	}
	
	public static void createTablesIfNotExist() throws IOException {
		Configuration configuration = new Configuration();
		createTablesIfNotExist(configuration);
	}

	public static void createTablesIfNotExist(Configuration configuration)
			throws IOException {
		HBaseAdmin admin = null;
		try {
			admin = new HBaseAdmin(configuration);
			createTable(admin, UserTable.NAME_BYTES, UserTable.FAM_MAIN);
			createTable(admin, TempUserTable.NAME_BYTES, UserTable.FAM_MAIN);
			createTable(admin, ArticleTable.NAME_BYTES, ArticleTable.FAM_MAIN);
			createTable(admin, RecommendationTable.NAME_BYTES, RecommendationTable.FAM_MAIN);
			createTable(admin, NeighbourTable.NAME_BYTES, NeighbourTable.FAM_MAIN);
		} finally {
			if (admin != null) {
				admin.close();
			}
		}
	}

}
